﻿using System;
using System.Linq;
using System.Windows.Forms;
using Usido.CRM.Core.ToolHelper;
using Usido.CRM.IRepository;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 库存查询 : Form
    {
        public 库存查询()
        {
            InitializeComponent();
        }
        #region 窗体绘制
        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁 
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        #endregion
        public string UserId { get; set; }
        public string UserName { get; set; }

        public 库存查询(string userId, string userName)
        {
            this.UserId = userId;
            this.UserName = userName;
            InitializeComponent();
        }

        private readonly IStockProductBalanceRepository stockProductBalance = new StockProductBalanceRepository();

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            BindData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BindData();
        }

        public void BindData()
        {
            string code = txtProductName.Text.Trim();
            string batchNumber = txtBatchNumber.Text.Trim();
            string where =
                $" WHERE (ProductCode like '%{code}%' or ProductName like '%{code}%') and (BatchNumber LIKE '%{batchNumber}%')";
            var stockBalanceList = stockProductBalance.GetStockBalanceList(where);
            Dgv_Ypyy.AutoGenerateColumns = false;
            Dgv_Ypyy.DataSource = stockBalanceList;

            var totalMoney = stockBalanceList.Sum(m => m.TotalMoney);
            lblTotalMoney.Text = "合计总金额：" + totalMoney.ToString();
        }

        private void 库存查询_Load(object sender, EventArgs e)
        {
            BindData();
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            BindData();
            var path = ExcelHelperForCs.ExportToExcel(Dgv_Ypyy, "库存详情");
            MessageBox.Show($"导出成功，文件路径:{path}");
        }
    }
}